package com.gdk.ksoft.assembly.receiver;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.baidu.android.pushservice.PushConstants;
import com.gdk.ksoft.R;
import com.gdk.ksoft.ui.mores.UpdateActivity;
import com.gdk.ksoft.assembly.utils.system.ApkUtils;
import com.google.gson.Gson;

/**
 * Created by hel on 2014-12-10.
 * 百度云推送信息广播
 */
public class BaiduPushReceiver extends BroadcastReceiver {

    public static final String TAG = BaiduPushReceiver.class.getSimpleName();

    public BaiduPushReceiver() {
        super();
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(PushConstants.ACTION_MESSAGE)) {
            try {
                //获取消息内容
                String message = intent.getExtras().getString(PushConstants.EXTRA_PUSH_MESSAGE_STRING);
                //消息的用户自定义内容读取方式
                Log.i(TAG, "onMessage: " + message);
                //自定义内容的 json 串
                Log.d(TAG, "EXTRA_EXTRA = " + intent.getStringExtra(PushConstants.EXTRA_EXTRA));
                String content = intent.getExtras().getString(PushConstants.EXTRA_EXTRA);//JSON字符串
                showNotification(context,content);//显示通知消息
            }catch (Exception e){
                e.printStackTrace();
                Toast.makeText(context,"更新发生错误!原因："+e.getMessage(),Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 显示通知消息
     * @param context
     * @param json
     */
    public void showNotification(Context context,String json){
        UpdateInfo updateInfo = new Gson().fromJson(json,UpdateInfo.class);//更新信息
        if(updateInfo.versionCode > ApkUtils.getVersionCode(context)) {//发布版本>该版本时推送更新提示
            Notification notification = new Notification();
            notification.defaults = Notification.DEFAULT_ALL;
            notification.icon = R.drawable.ic_launcher;
            notification.flags = Notification.FLAG_AUTO_CANCEL;
            notification.when = System.currentTimeMillis();
            Intent intentGo = new Intent(context, UpdateActivity.class);
            intentGo.putExtra("downloadUrl", updateInfo.downloadUrl);
            notification.setLatestEventInfo(context, updateInfo.title, updateInfo.content,
                    PendingIntent.getActivity(context, 0, intentGo, 0));
            ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE))
                    .notify(2, notification);
        }
    }

    /**
     * 更新信息实体类
     */
    public class UpdateInfo{
        public String title;//标题
        public String content;//更新内容
        public int versionCode;//软件版本
        public String downloadUrl;//更新地址
    }
}
